package com.ruoyi.web.controller.cms.common;


import com.ruoyi.cms.article.domain.vo.WangEditorUploadResultVo;
import com.ruoyi.cms.fileInfo.controller.FileInfoController;
import com.ruoyi.cms.fileInfo.domain.CmsFileInfo;
import com.ruoyi.cms.fileInfo.service.ICmsFileInfoService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.DecimalFormat;

@RestController("AdminCmsCommonController")
@RequestMapping("/admin/cms/common")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(FileInfoController.class);


    @Resource
    private ServerConfig serverConfig;

    @Resource
    private ICmsFileInfoService cmsFileInfoService;


    /**
     * 针对CMS模块的上传请求
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);

            /**
             * 此处相对于若依原有的
             */
            /*新增文件管理*/
            CmsFileInfo cmsFileInfo = new CmsFileInfo();
            int newFileNameSeparatorIndex = fileName.lastIndexOf("/");
            String newFileName = fileName.substring(newFileNameSeparatorIndex + 1).toLowerCase();
            int separatorIndex = newFileName.lastIndexOf(".");
            String suffix = newFileName.substring(separatorIndex + 1).toLowerCase();

            LoginUser loginUser = SecurityUtils.getLoginUser();

            // 计算文件大小信息
            long size = file.getSize();
            String fileSizeInfo = "0kB";
            if (size != 0) {
                String[] unitNames = new String[]{"B", "kB", "MB", "GB", "TB", "EB"};
                int digitGroups = Math.min(unitNames.length - 1, (int) (Math.log10(size) / Math.log10(1024)));
                fileSizeInfo = new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups)) + " " + unitNames[digitGroups];
            }
            cmsFileInfo.setFileOriginName(file.getOriginalFilename());
            cmsFileInfo.setFileSuffix(suffix);
            cmsFileInfo.setFileSizeInfo(fileSizeInfo);
            cmsFileInfo.setFileObjectName(newFileName);
            cmsFileInfo.setFilePath(fileName);
            cmsFileInfo.setDelFlag("N");
            cmsFileInfo.setCreateBy(loginUser.getUsername());
            cmsFileInfoService.insertCmsFileInfo(cmsFileInfo);
            Long fileId = cmsFileInfo.getFileId();
            ajax.put("fileId", fileId);
            ajax.put("fileOriginName", file.getOriginalFilename());
            ajax.put("fileSuffix", suffix);
            ajax.put("fileSize", fileSizeInfo);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 针对wangEditor的上传文件的请求
     */
    @PostMapping("/wangEditor/upload/file")
    public AjaxResult WangEditorUploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            WangEditorUploadResultVo vo = new WangEditorUploadResultVo();
            vo.setUrl(url);
            /**
             * 此处相对于若依原有的
             */
            /*新增文件管理*/
            CmsFileInfo cmsFileInfo = new CmsFileInfo();
            int newFileNameSeparatorIndex = fileName.lastIndexOf("/");
            String newFileName = fileName.substring(newFileNameSeparatorIndex + 1).toLowerCase();
            int separatorIndex = newFileName.lastIndexOf(".");
            String suffix = newFileName.substring(separatorIndex + 1).toLowerCase();

            LoginUser loginUser = SecurityUtils.getLoginUser();

            // 计算文件大小信息
            long size = file.getSize();
            String fileSizeInfo = "0kB";
            if (size != 0) {
                String[] unitNames = new String[]{"B", "kB", "MB", "GB", "TB", "EB"};
                int digitGroups = Math.min(unitNames.length - 1, (int) (Math.log10(size) / Math.log10(1024)));
                fileSizeInfo = new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups)) + " " + unitNames[digitGroups];
            }
            cmsFileInfo.setFileOriginName(file.getOriginalFilename());
            cmsFileInfo.setFileSuffix(suffix);
            cmsFileInfo.setFileSizeInfo(fileSizeInfo);
            cmsFileInfo.setFileObjectName(newFileName);
            cmsFileInfo.setFilePath(fileName);
            cmsFileInfo.setDelFlag("N");
            cmsFileInfo.setCreateBy(loginUser.getUsername());
            cmsFileInfoService.insertCmsFileInfo(cmsFileInfo);
            Long fileId = cmsFileInfo.getFileId();
            ajax.put("fileId", fileId);
            ajax.put("fileOriginName", file.getOriginalFilename());
            ajax.put("fileSuffix", suffix);
            ajax.put("fileSize", fileSizeInfo);
            ajax.put("errno", 0);
            /*结束*/

            /*结束*/
            ajax.put("data", vo);

            return ajax;
        } catch (Exception e) {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("errno", 1);
            ajax.put("message", "上传失败:" + e.getMessage());
            return ajax;
        }
    }
}
